package com.kongge.viewdisplayframeworklib.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kongge.viewdisplayframeworklib.R;

public class TabWidget extends LinearLayout {

	private TabListener mTabListener;
	private int currentIndex = 0;

	public interface TabListener {
		public void onClick(int oldIndex, int newIndex);
	}

	public TabWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public TabWidget(Context context) {
		super(context);
	}

	public void setTabListener(TabListener listener) {
		mTabListener = listener;
	}

	public void addSubTab(String text, Drawable drawable) {
		LayoutInflater inflater = LayoutInflater.from(getContext());
		View child = inflater.inflate(R.layout.tab_item, this, false);
		TextView textView = (TextView) child.findViewById(R.id.tabitem_title);
		textView.setTextColor(getResources().getColorStateList(R.drawable.tab_item_textcolor));
		textView.setText(text);
		child.setClickable(true);
		child.setTag(getChildCount() + "");
		
		ImageView imageView = (ImageView) child.findViewById(R.id.tabitem_image);
		imageView.setBackgroundDrawable(drawable);
		
		this.addView(child);
		child.setOnClickListener(new TabClickListener(getChildCount() - 1));
	}
	
	public void requestTabFocus(int index) {
		getChildAt(currentIndex).setSelected(false);
		currentIndex = index;
		getChildAt(currentIndex).setSelected(true);
	}

	private class TabClickListener implements OnClickListener {

		private final int mTabIndex;

		public TabClickListener(int nIndex) {
			mTabIndex = nIndex;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (mTabListener != null) {
				mTabListener.onClick(currentIndex, mTabIndex);
				requestTabFocus(mTabIndex);
			}

		}

	}

}
